package com.easyssh.framework.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 页面参数处理
 * @ClassName: PageParamsUtil
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author liangyuanbing
 * @date 2015年12月18日
 *
 */
public final class PageParamsUtil {
	
	private final static Logger LOG = LoggerFactory.getLogger(PageParamsUtil.class);

	public static Map<String, String> getParamsInRequest() {
		HttpServletRequest request = ServletActionContext.getRequest();
		Enumeration<?> paramNames = request.getParameterNames();
		Map<String, String> params = new HashMap<String, String>();
		while (paramNames.hasMoreElements()) {
			String name = (String) paramNames.nextElement();
			params.put(name, StringUtils.trimToEmpty(request.getParameter(name)));
		}
		return params;
	}

	public static String marshareParamsMapToURLStr(Map<String, String> params) {
		Iterator<String> iterator = params.keySet().iterator();
		StringBuffer buffer = new StringBuffer();
		while(iterator.hasNext()) {
			String key = iterator.next();
			buffer.append(key);
			buffer.append("=");
			buffer.append(params.get(key));
			if(iterator.hasNext()) {
				buffer.append("&");
			}
		}
		return buffer.toString();
	}

	public static String urlEncode(String s, String enc) {
		String value = "";
		try {
			value = URLEncoder.encode(s, enc);
		} catch (UnsupportedEncodingException e) {
			LOG.error("[INFO]SignHandler -- urlEncode : remove the parameter to URLStr : "
							+ s
							+ " for the value is can not be URLEncoded to UTF-8 string ");
		}

		value = value.replace("*", "%2A");
		value = value.replace("-", "%2D");
		value = value.replace("_", "%5F");
		value = value.replace(".", "%2E");
		return value;
	}

	public static boolean isEmpty(String str) {
		return StringUtils.isEmpty(str);
	}

	public static boolean isNumber(String str) {
		return NumberUtils.isNumber(str);
	}

}